#include <my_header.h>

int main(){
    char *ip = "192.168.75.128";
    char *port = "8080";

    int socket_fd = socket(AF_INET, SOCK_STREAM, 0);

    struct sockaddr_in sockaddr;
    sockaddr.sin_family = AF_INET;
    sockaddr.sin_port = htons(atoi(port));
    sockaddr.sin_addr.s_addr = inet_addr(ip);

    connect(socket_fd, (struct sockaddr *)&sockaddr, sizeof(sockaddr));


    // 接收文件大小
    off_t file_size;
    int ret=recv(socket_fd, &file_size, sizeof(off_t), MSG_WAITALL);
    ERROR_CHECK(ret,-1,"ret_recv");
    printf("file_size: %ld %d\n", file_size,ret);


    // 先读取文件名字长度
    // 再根据文件名字长度: 读取文件名
    int file_name_len ;
    int len_ret=recv(socket_fd, &file_name_len, sizeof(int), 0);
    ERROR_CHECK(len_ret,-1,"len_ret");
    printf("%d\n",len_ret);
    char file_name[60] = {0};
    int ret_recv=recv(socket_fd, file_name, file_name_len, 0);
    ERROR_CHECK(ret_recv,-1,"ret_recv");
    int file_fd = open(file_name, O_RDWR|O_CREAT, 0600);

    // 文件调整需要的大小
    ftruncate(file_fd, file_size);

    char *p = (char *)mmap(NULL, file_size, PROT_READ|PROT_WRITE, MAP_SHARED, file_fd, 0);
    recv(socket_fd, p, file_size, MSG_WAITALL);
    munmap(p, file_size);

    close(file_fd);
    close(socket_fd);
    return 0;
}


